package com.example.demo.service;

import com.example.demo.dao.UserRepository;
import com.example.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> search() {
        return userRepository.findAll();
    }
    //事务管理，放置多用户抢占干扰。出现异常，会事务回滚。
    @Transactional(rollbackFor = Exception.class)
    @Override
    public User add(User user) {
        return userRepository.saveAndFlush(user);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public User deleteById(int id) {
        Optional<User> byId = userRepository.findById(id);
        User user = byId.get();
        userRepository.deleteById(user.getId());
        return user;
    }

    @Transactional
    @Override
    public User update(User user) {
        userRepository.save(user);
        return user;
    }
}
